<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>断网守护</title>
  <!-- Tell the browser to be responsive to screen width -->
  <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  <!-- Bootstrap 3.3.7 -->
  <link rel="stylesheet" href="css/bootstrap.min.css">
  <!-- Font Awesome -->
  <link rel="stylesheet" href="css/font-awesome.min.css">
  <!-- Theme style -->
  <link rel="stylesheet" href="css/AdminLTE.min.css">
  <!-- iCheck -->
  <link rel="stylesheet" href="plugins/iCheck/square/blue.css">

  <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
  <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  <!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  <![endif]-->

  <!-- Google Font -->
  <!-- <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600,700,300italic,400italic,600italic"> -->
</head>
<body class="hold-transition login-page">
<div class="login-box">
  <div class="login-logo">
    <a href="#"><b>断网</b>守护 v2.0.3</a>
  </div>
  <!-- /.login-logo -->
  <div class="login-box-body">
    <p id="remain-text" class="login-box-msg"></p><p id="tips-text" class="login-box-msg">请输入账号密码点击开始守护</p>
      <div class="form-group has-feedback">
        <input id="account" type="account" class="form-control" placeholder="账号">
        <span class="glyphicon glyphicon-envelope form-control-feedback"></span>
      </div>
      <div class="form-group has-feedback">
        <input id="password" type="password" class="form-control" placeholder="密码">
        <span class="glyphicon glyphicon-lock form-control-feedback"></span>
      </div>
      <div class="row">
        <div class="col-xs-8">
          <div class="checkbox icheck">
            <label>
              <input id="is-remember" type="checkbox" checked="true"> 记住密码
            </label>
          </div>
        </div>
        <!-- /.col -->
        <div class="col-xs-4">
          <button id="test-button" type="button" onclick="reconnect()" class="btn btn-info btn-block btn-flat">测试账号</button>
          <button id="start-button" type="button" onclick="switch_guard()" class="btn btn-primary btn-block btn-flat">开始</button>
        </div>
        <!-- /.col -->
      </div>
  </div>
  <!-- /.login-box-body -->
</div>
<!-- /.login-box -->

<!-- jQuery 3 -->
<script src="js/jquery.min.js"></script>
<script>if (typeof module === 'object') { window.jQuery = window.$ = module.exports; };</script>
<!-- Bootstrap 3.3.7 -->
<script src="js/bootstrap.min.js"></script>
<!-- iCheck -->
<script src="plugins/iCheck/icheck.min.js"></script>
<script>
  var check_interval = 300;
  var remain_time = check_interval;
  var running_id = -1;
  const ipc = require('electron').ipcRenderer
  const Store = require('electron-store');
  const data_store = new Store();
  Date.prototype.Format = function(fmt){
    var o = {
        "M+": this.getMonth()+1,
        "d+": this.getDate(),
        "H+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "S+": this.getMilliseconds()
    };
    //因为date.getFullYear()出来的结果是number类型的,所以为了让结果变成字符串型，下面有两种方法：
    if(/(y+)/.test(fmt)){
        //第一种：利用字符串连接符“+”给date.getFullYear()+""，加一个空字符串便可以将number类型转换成字符串。
        fmt=fmt.replace(RegExp.$1,(this.getFullYear()+"").substr(4-RegExp.$1.length));
    }
    for(var k in o){
        if (new RegExp("(" + k +")").test(fmt)){
            //第二种：使用String()类型进行强制数据类型转换String(date.getFullYear())，这种更容易理解。
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(String(o[k]).length)));
        }
    }
    return fmt;
  };
  $(function () {
    $('input').iCheck({
      checkboxClass: 'icheckbox_square-blue',
      radioClass: 'iradio_square-blue',
      increaseArea: '20%' /* optional */
    });
    let account = data_store.get("account");
    let password = data_store.get("password");
    if(account!=undefined && account.length > 0 && password != undefined && password.length > 0){
      $("#start-button").html("停止");
      remain_time = check_interval;
      running_id = setInterval("time_tick()",1000);
      $("#account").val(account);
      $("#password").val(password);
    }
    $.ajaxSetup({cache:false});
  });

  function switch_guard(){
    if($("#start-button").html() == "停止"){
      $("#start-button").html("开始");
      $("#tips-text").html("请输入账号密码点击开始守护");
      window.clearInterval(running_id);
      running_id = -1;
    }else{
      $("#start-button").html("停止");
      remain_time = check_interval;
      if($("#is-remember").is(':checked')){
        data_store.set('account', $("#account").val());
        data_store.set('password', $("#password").val());
      }else{
        data_store.set('account', "");
        data_store.set('password', "");
      }
      running_id = setInterval("time_tick()",1000);
    }
  }

  function time_tick(){
    remain_time --;
    $("#remain-text").html(remain_time);
    if(remain_time <= 0){
      check_network();
      remain_time = check_interval;
    }
  }

  function check_network(){
    $.ajax({
        type: "GET",
        url: "http://news.baidu.com?_=" + new Date().getTime(),
        dataType: "html",
        success: function(data){
          console.log(data.length);
          if(data.length > 1000){
            $("#tips-text").html("网络畅通");
          }else{
            $("#tips-text").html("账号掉线，重新登陆中。");
            data_store.set('offline' + (new Date()).Format("yyyy-MM-dd HH:mm:ss.S"),data);
            reconnect();
          }
        },
        error: function(data){
          $("#tips-text").html("网断了，重新登陆中。");
          data_store.set('error' + (new Date()).Format("yyyy-MM-dd HH:mm:ss.S"),data);
          reconnect();
        }
    });
  }

  function reconnect(){
    let account = $("#account").val();
    let password = $("#password").val();
    if(account!=undefined && account.indexOf("@") != -1){
      ipc.send('open-reconnect-window',{"account":account,"password":password});
    }else{
      $.ajax({
        type: "POST",
        url: "http://172.18.50.22:8080/portal/pws?t=li&ifEmailAuth=false",
        contentType: "application/x-www-form-urlencoded; charset=UTF-8",
        data:{
          "userName":account,
          "userPwd":i_p_f_base64Encode(password),
          "userDynamicPwd":"",
          "userDynamicPwdd":"",
          "serviceTypeHIDE":"",
          "serviceType":"",
          "userurl":"",
          "userip":"",
          "basip":"",
          "language":"Chinese",
          "usermac":"null",
          "wlannasid":"",
          "wlanssid":"",
          "entrance":"null",
          "loginVerifyCode":"",
          "userDynamicPwddd":"",
          "customPageId":"102",
          "pwdMode":"0",
          "portalProxyIP":"172.18.50.22",
          "portalProxyPort":"50200",
          "dcPwdNeedEncrypt":"1",
          "assignIpType":"0",
          "appRootUrl":"http://172.18.50.22:8080/portal/",
          "manualUrl":"",
          "manualUrlEncryptKey":""
        },
        dataType: "text",
        beforeSend: function(xhr) {
        //  xhr.setRequestHeader("Cookie", "hello1=" + $("#account").val() + "; hello2=false");
          xhr.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.9");
         // xhr.setRequestHeader("Accept-Encoding", "gzip, deflate");
        },
        success: function(data){
          jsonstr = i_p_f_base64DecodeAndUrlDecode(data);
          if(jsonstr.indexOf("portServIncludeFailedReason")!=-1){
            $("#tips-text").html("账号密码错误！");
          }else{
            $("#tips-text").html("登陆成功");
          }
        },
        error: function(data){
          $("#tips-text").html("登陆异常");
        }
    });
    }
  }

  var base64EncodeChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
  var base64DecodeChars = new Array(
      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
      -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 62, -1, -1, -1, 63,
      52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, -1, -1, -1, -1,
      -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
      15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1,
      -1, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40,
      41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, -1, -1, -1, -1, -1);

  function i_p_f_base64Encode(str) {
    var out, i, len;
    var c1, c2, c3;

    len = str.length;
    i = 0;
    out = "";
    while(i < len) {
    c1 = str.charCodeAt(i++) & 0xff;
    if(i == len)
    {
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt((c1 & 0x3) << 4);
        out += "==";
        break;
    }
    c2 = str.charCodeAt(i++);
    if(i == len)
    {
        out += base64EncodeChars.charAt(c1 >> 2);
        out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
        out += base64EncodeChars.charAt((c2 & 0xF) << 2);
        out += "=";
        break;
    }
    c3 = str.charCodeAt(i++);
    out += base64EncodeChars.charAt(c1 >> 2);
    out += base64EncodeChars.charAt(((c1 & 0x3)<< 4) | ((c2 & 0xF0) >> 4));
    out += base64EncodeChars.charAt(((c2 & 0xF) << 2) | ((c3 & 0xC0) >>6));
    out += base64EncodeChars.charAt(c3 & 0x3F);
    }
    return out;
  }

  function i_p_f_base64DecodeAndUrlDecode(str) {
	  return decodeURIComponent(i_p_f_base64Decode(str));
  }
  /*    */
  function i_p_f_base64Decode(str) {
    var c1, c2, c3, c4;
    var i, len, out;

    len = str.length;
    i = 0;
    out = "";
    while(i < len) {
    /* c1 */
    do {
        c1 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
    } while(i < len && c1 == -1);
    if(c1 == -1)
        break;

    /* c2 */
    do {
        c2 = base64DecodeChars[str.charCodeAt(i++) & 0xff];
    } while(i < len && c2 == -1);
    if(c2 == -1)
        break;

    out += String.fromCharCode((c1 << 2) | ((c2 & 0x30) >> 4));

    /* c3 */
    do {
        c3 = str.charCodeAt(i++) & 0xff;
        if(c3 == 61)
        return out;
        c3 = base64DecodeChars[c3];
    } while(i < len && c3 == -1);
    if(c3 == -1)
        break;

    out += String.fromCharCode(((c2 & 0XF) << 4) | ((c3 & 0x3C) >> 2));

    /* c4 */
    do {
        c4 = str.charCodeAt(i++) & 0xff;
        if(c4 == 61)
        return out;
        c4 = base64DecodeChars[c4];
    } while(i < len && c4 == -1);
    if(c4 == -1)
        break;
    out += String.fromCharCode(((c3 & 0x03) << 6) | c4);
    }
    return out;
  }
</script>
</body>
</html>
